﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;		//Allows us to use Lists. 
using UnityEngine.UI;					//Allows us to use UI.

public class MapManager : MonoBehaviour {

	public GameObject[] outWallArray;
	public GameObject[] floorArray;
	public GameObject[] wallArray;

	public int rows= 10;
	public int cols= 10;

	public int minWallCount = 2;
	public int maxWallCount = 8;

	private Transform mapContainer;//地图容器
	private List<Vector2> positionList = new List<Vector2>();

	// Use this for initialization
	void Start () {
		InitMap ();
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	//初始化地图
	private void InitMap(){
		mapContainer = new GameObject ("Map").transform;

		//下面是创建围墙和地板
		for (int x=0; x<cols; x++) {
			for(int y=0; y<rows; y++){
				int index;
				GameObject go;
				//判断是否是外围墙
				if(x==0 || y==0 || x==cols-1 || y==rows-1){
					index = Random.Range(0, outWallArray.Length);
					go = GameObject.Instantiate(outWallArray[index], new Vector3(x,y,0),Quaternion.identity) as GameObject;
					//go.transform.parent = mapContainer;
					go.transform.SetParent(mapContainer);
				}else{
					//地板
					index = Random.Range(0, floorArray.Length);
					go = GameObject.Instantiate(floorArray[index], new Vector3(x,y,0),Quaternion.identity) as GameObject;
					//go.transform.parent = mapContainer;
					go.transform.SetParent(mapContainer);
				}

			}
		}

		//创建障碍物、食物、敌人

		//清空位置历史
		positionList.Clear ();
		for (int x=2; x<cols-2; x++) {
			for(int y=2; y<rows-2; y++){
				positionList.Add(new Vector2(x,y));
			}
		}
		//添加障碍物--墙

		//随机障碍物个数
		int wallCount = Random.Range (minWallCount, maxWallCount + 1);
		for (int i=0; i<wallCount; i++) {
			//随机取得位置
			int posIndex = Random.Range(0, positionList.Count);
			Vector2 pos = positionList[posIndex];

			//已占用位置清除
			positionList.RemoveAt(posIndex);

			//随机取得障碍物
			int wallIndex = Random.Range(0, wallArray.Length);

			GameObject go = GameObject.Instantiate(wallArray[wallIndex], new Vector3(pos.x,pos.y,0),Quaternion.identity) as GameObject;
			go.transform.SetParent(mapContainer);
		}
	}
}
